from odoo import models, fields, api, _
from odoo.exceptions import AccessDenied, ValidationError
import logging

_logger = logging.getLogger(__name__)


class ResUsers(models.Model):
    _inherit = 'res.users'
    
    # 钉钉相关字段 - 第一次启用时需要通过命令行升级
    # 步骤：
    # 1. 取消下面的注释
    # 2. 运行: docker compose stop odoo
    # 3. 运行: docker compose run --rm odoo odoo -c /etc/odoo/odoo.conf -d odootest -u dingtalk_integration --stop-after-init
    # 4. 运行: docker compose start odoo
    
    dingtalk_userid = fields.Char(string="钉钉 UserID", index=True, copy=False,
                                  help="钉钉系统中的用户ID，用于钉钉登录")
    dingtalk_unionid = fields.Char(string="钉钉 UnionID", index=True, copy=False,
                                   help="钉钉开放平台的唯一ID")
    dingtalk_employee_id = fields.Many2one('dingtalk.employee', string="关联钉钉员工",
                                          readonly=True, help="对应的钉钉员工记录")
    
    _sql_constraints = [
        ('dingtalk_userid_unique', 'unique(dingtalk_userid)', '钉钉 UserID 必须唯一！'),
    ]
    
    @api.model
    def _auth_oauth_signin_dingtalk(self, provider, validation, params):
        """钉钉 OAuth 登录处理"""
        _logger.info("=" * 80)
        _logger.info("🔐 钉钉 OAuth 登录")
        _logger.info("=" * 80)
        _logger.info(f"Provider: {provider}")
        _logger.info(f"Validation: {validation}")
        _logger.info(f"Params: {params}")
        
        # 从钉钉获取的用户信息
        dingtalk_userid = validation.get('userid')
        unionid = validation.get('unionid')
        
        if not dingtalk_userid:
            raise AccessDenied(_('无法从钉钉获取用户信息'))
        
        # 查找已有用户
        user = self.search([('dingtalk_userid', '=', dingtalk_userid)], limit=1)
        
        if user:
            _logger.info(f"✅ 找到已有用户: {user.login}")
            return user.login
        
        # 尝试通过钉钉员工记录查找
        employee = self.env['dingtalk.employee'].sudo().search([
            ('userid', '=', dingtalk_userid)
        ], limit=1)
        
        if employee and employee.user_id:
            # 更新用户的钉钉 UserID
            employee.user_id.sudo().write({
                'dingtalk_userid': dingtalk_userid,
                'dingtalk_unionid': unionid,
                'dingtalk_employee_id': employee.id,
            })
            _logger.info(f"✅ 关联到已有用户: {employee.user_id.login}")
            return employee.user_id.login
        
        # 用户不存在，需要先在系统中创建
        raise AccessDenied(_(
            '该钉钉账号尚未关联到 Odoo 用户。\n\n'
            '请联系管理员将您的钉钉账号转换为系统用户。\n\n'
            '钉钉 UserID: %s'
        ) % dingtalk_userid)
    
    def write(self, vals):
        """覆盖 write 方法，同步更新钉钉员工关联"""
        result = super(ResUsers, self).write(vals)
        
        # 如果设置了 dingtalk_userid，尝试关联钉钉员工
        if 'dingtalk_userid' in vals and vals['dingtalk_userid']:
            for user in self:
                if not user.dingtalk_employee_id:
                    employee = self.env['dingtalk.employee'].sudo().search([
                        ('userid', '=', vals['dingtalk_userid'])
                    ], limit=1)
                    if employee:
                        user.sudo().write({
                            'dingtalk_employee_id': employee.id,
                        })
                        employee.sudo().write({
                            'user_id': user.id,
                        })
        
        return result

